package com.idbk.chargestation.activity.pile;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.user.ActivityLogin;
import com.idbk.chargestation.activity.user.ActivityMyFavorite;
import com.idbk.chargestation.adapter.SearchHistoryAdapter;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.bean.JsonPointsList;
import com.idbk.chargestation.db.SearchHistoryDatabase;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.CheckUtil;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;

import java.util.List;

/**
 * 关键字搜索
 * @author lupc
 *
 */

public class ActivityKeyWordSearch extends Activity implements
OnClickListener,OnEditorActionListener {

	private EditText mEditSearch;

	private Context mContext;

	private ListView mListView;		
	/**
	 * 历史记录 头部操作控件
	 */
	private ListViewHeaderHold mHeaderHold;
	/**
	 * 历史记录 底部操作控件
	 */
	private ListViewFooterHold mFooterHold;

	private SearchHistoryAdapter mHistoryAdapter;

	private List<SearchHistoryDatabase.KeywordItem> mSearchData;

	private SearchHistoryDatabase mSearchDb;

	private int mPageIndex = 1;

	public final static int PAGE_SIZE = 5;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_keyword_search);

		mContext = ActivityKeyWordSearch.this;

		setupView();

		setupData();
	}

	private void setupView() {
		mEditSearch = (EditText) findViewById(R.id.edittext_search);
		if (mEditSearch != null) {
			mEditSearch.setOnEditorActionListener(this);
		}
		mListView = (ListView) findViewById(R.id.searchlist);

		findViewById(R.id.toolbar_back).setOnClickListener(this);
		findViewById(R.id.imageview_search).setOnClickListener(this);			
	}

	private void setupData(){
		mSearchDb = new SearchHistoryDatabase(this);

		setupListViewHeader();
		setupListViewFooter();

		refreshHeader();
		refreshHistoryData();
	}

	private void setupListViewHeader(){
		mHeaderHold = new ListViewHeaderHold();
		View h = LayoutInflater.from(mContext).inflate(R.layout.item_search_collection, mListView, false);
		mHeaderHold.textTip = (TextView)h.findViewById(R.id.textview_tip);

		mHeaderHold.layoutMyCollection = (LinearLayout)h.findViewById(R.id.layout_collection);
		mHeaderHold.layoutCollection1 = (LinearLayout)h.findViewById(R.id.layout_collection_1);

		mHeaderHold.textMyCollection = (TextView)mHeaderHold.layoutMyCollection.findViewById(R.id.textview_my_colletion);
		mHeaderHold.textMyCollection.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext,ActivityMyFavorite.class);
				startActivity(intent);
			}
		});		

		mHeaderHold.textMyCollection1Name = (TextView)mHeaderHold.layoutMyCollection.findViewById(R.id.textview_mycollection_1_name);
		mHeaderHold.textMyCollection1Address = (TextView)mHeaderHold.layoutMyCollection.findViewById(R.id.textview_mycollection_1_address);

		mHeaderHold.progress = h.findViewById(R.id.layout_progress);


		mListView.addHeaderView(h);		
	}

	private void setupListViewFooter(){
		mFooterHold = new ListViewFooterHold();
		View bottom = LayoutInflater.from(mContext).inflate(R.layout.item_search_history_bottom, mListView, false);
		mFooterHold.t1 = bottom.findViewById(R.id.layout_search_more);
		mFooterHold.t1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				List<SearchHistoryDatabase.KeywordItem> data = mSearchDb.select(mPageIndex + 1, PAGE_SIZE);
				if(data.size() == PAGE_SIZE){
					mPageIndex++;
					mSearchData.addAll(data);
					mHistoryAdapter.notifyDataSetChanged();
				} else {
					mFooterHold.t1.setVisibility(View.GONE);
					if(data.size() != 0){
						mPageIndex++;
						mSearchData.addAll(data);
						mHistoryAdapter.notifyDataSetChanged();
					}
				}
			}
		});
		mFooterHold.t2 = (TextView)bottom.findViewById(R.id.textview_search_clean);
		mFooterHold.t2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mSearchDb.deleteAll();
				mSearchData.clear();
				mHistoryAdapter.notifyDataSetChanged();

				mFooterHold.t1.setVisibility(View.GONE);
				mFooterHold.t2.setVisibility(View.GONE);
			}
		});
		mListView.addFooterView(bottom);		
	}


	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if(actionId == EditorInfo.IME_ACTION_SEARCH) {
			searchKeyword();
			return true;
		}
		return false;
	}

	@Override
	public void onClick(View view) {
		switch(view.getId()) {		
		case R.id.toolbar_back://退出
			finish();
			break;
		case R.id.imageview_search:
			searchKeyword();
			break;
		}		
	}

	private void refreshHeader(){
		mHeaderHold.progress.setVisibility(View.VISIBLE);
		mHeaderHold.textTip.setVisibility(View.GONE);
		mHeaderHold.layoutMyCollection.setVisibility(View.GONE);

		ChargeStationAPI.getMyPointCollections(1, 1, new EHttpResponse() {

			@Override
			public void onEResponse(String response) {
				final JsonPointsList result = GsonUtils.toBean(JsonPointsList.class, response);
				if(result == null){
					mHeaderHold.progress.setVisibility(View.GONE);
					mHeaderHold.layoutMyCollection.setVisibility(View.GONE);
					mHeaderHold.textTip.setVisibility(View.VISIBLE);

					mHeaderHold.textTip.setText("无法获取数据！");
				} else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()
						|| result.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {
					mHeaderHold.progress.setVisibility(View.GONE);
					mHeaderHold.layoutMyCollection.setVisibility(View.GONE);
					mHeaderHold.textTip.setVisibility(View.VISIBLE);

					mHeaderHold.textTip.setText(CheckUtil.textFromHtml("还没登录，<font color='#5dd139'>马上登录</font>"));
					mHeaderHold.textTip.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent intent = new Intent(mContext, ActivityLogin.class);
							startActivityForResult(intent, Const.CODE_REQUEST_LOGIN);
						}
					});
				} else if (result.status == GlobalResult.OK.getStatus()) {
					if (result.points != null && result.points.size() > 0) {
						mHeaderHold.progress.setVisibility(View.GONE);
						mHeaderHold.textTip.setVisibility(View.GONE);
						mHeaderHold.layoutMyCollection.setVisibility(View.VISIBLE);

						mHeaderHold.textMyCollection.setText("查看全部" + result.total + "个收藏");

						mHeaderHold.textMyCollection1Name.setText(result.points.get(0).name);
						mHeaderHold.textMyCollection1Address.setText(result.points.get(0).address);
						mHeaderHold.layoutCollection1.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent intent = new Intent(mContext, ActivityPointDetail.class);
								intent.putExtra(Const.KEY_ID, result.points.get(0).id);
								startActivity(intent);
							}
						});
					} else {
						//返回的是空集合，表示没有收藏
						mHeaderHold.progress.setVisibility(View.GONE);
						mHeaderHold.layoutMyCollection.setVisibility(View.GONE);
						mHeaderHold.textTip.setVisibility(View.VISIBLE);
						mHeaderHold.textTip.setText("当前没有收藏，赶紧去收藏吧！");
					}
				} else {
					mHeaderHold.progress.setVisibility(View.GONE);
					mHeaderHold.layoutMyCollection.setVisibility(View.GONE);
					mHeaderHold.textTip.setVisibility(View.VISIBLE);
					mHeaderHold.textTip.setText("无法获取数据！");
				}
			}

		});
	}

	private void refreshHistoryData(){
		mPageIndex = 1;
		mSearchData = mSearchDb.select(mPageIndex, PAGE_SIZE);
		mHistoryAdapter = new SearchHistoryAdapter(this,mSearchData,mSearchDb);
		mListView.setAdapter(mHistoryAdapter);

		refreshFooter();
	}

	private void refreshFooter(){
		if(mSearchData.size() == 0){
			mFooterHold.t1.setVisibility(View.GONE);
			mFooterHold.t2.setVisibility(View.GONE);
		} else if(mSearchData.size() < PAGE_SIZE){
			mFooterHold.t1.setVisibility(View.GONE);
			mFooterHold.t2.setVisibility(View.VISIBLE);
		} else if(mSearchData.size() >= PAGE_SIZE){
			mFooterHold.t1.setVisibility(View.VISIBLE);
		}
	}

	private void searchKeyword(){	
		String keyword = mEditSearch.getText().toString();
		if("".equals(keyword) || keyword.length() > 20){
			return;
		}

		mSearchDb.insert(keyword);
		refreshHistoryData();

		Intent intent = new Intent(this,ActivityPointList.class);
		intent.putExtra(ActivityPointList.KEY_MODEL, ActivityPointList.MODEL_KEYWORD);
		intent.putExtra(ActivityPointList.KEY_KEYWORD, keyword);
		startActivity(intent);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mSearchDb != null){
			mSearchDb.close();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == Const.CODE_REQUEST_LOGIN && resultCode == Const.CODE_RESPONSE_LOGIN_SUCCESS){
			refreshHeader();
		}
	}

	private static class ListViewHeaderHold {
		private TextView textTip;

		private LinearLayout layoutMyCollection;
		private LinearLayout layoutCollection1;
		private TextView textMyCollection1Name;
		private TextView textMyCollection1Address;

		private TextView textMyCollection;

		private View progress;
	}

	private static class ListViewFooterHold {
		/**
		 * 加载更多
		 */
		private View t1;

		/**
		 * 清除
		 */
		private TextView t2;
	}

}

